package com.zzx.boot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzx.boot.common.R;
import com.zzx.boot.pojo.Employee;
import com.zzx.boot.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

//表示这是一个控制层
@Controller
//设置请求路径是
@RequestMapping("/employee")
//设置该类不会跳转页面 返回值只会写json数据
@ResponseBody
@Slf4j
public class EmployeeController {
    @Resource
    private EmployeeService service;

    /**
     * 登录请求
     * @param request 将登录成功的id存储到session中
     * @param employee 将请求体中的数据封装在employee中
     * @return 返回是否成功
     */
    @PostMapping("/login")
    /* @RequestBody 是把请求体中的数据封装到employee中*/
    public  R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
            R<Employee> login = service.login(employee);
        HttpSession session = request.getSession();
       if (login.getCode()==1){
               session.setAttribute("employee", login.getData().getId());

//           使session无效
//           session.invalidate();
//           Object employee1 = session.getAttribute("employee");
//           System.out.println("session"+employee1);
       }
        return login;
    }

    /**
     * 员工登出请求
     * @param session 清除session数据
     * @return 返回是否成功
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("employee");

        return R.success("退出登录");
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee){
        R<String> stringR = service.addUser(employee);
        return stringR;
    }

    /**
     * 显示分页列表
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
        log.info("page={} pageSize={}  name=",page,pageSize,name);
        return service.pageSelect(page, pageSize, name);
    }


    /**
     * 更新员工状态
     * @param
     * @param employee
     * @return
     */
    @PutMapping
    @Transactional
    public R<String> status(@RequestBody Employee employee){
        R<String> stringR = service.IsStatus(employee);
        return stringR;
    }

    @GetMapping("/{id}")
    public R<Employee> updateById(@PathVariable("id") String id){
        log.info(id);
        Employee byId = service.getById(id);
        return byId!=null?R.success(byId):R.error("用户获取失败");
    }
}
